package com.example.klinemqflink.service;

import com.example.klinemqflink.config.RabbitMQConfig;
import com.example.klinemqflink.model.MarketData;
import com.example.klinemqflink.utils.LocalTimeUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ForexMarketSimulator {

    @Resource
    ObjectMapper objectMapper;

    @Autowired
    RabbitMQProducer rabbitMQProducer;

    public static final String ROUTING_KEY = "market.data.";

    // 增加更多的货币对
    private static final String[] FOREX_PAIRS = {
            "EUR/USD", "GBP/USD", "USD/JPY", "AUD/USD", "USD/CAD",
            "EUR/GBP", "USD/CHF", "NZD/USD", "EUR/JPY", "GBP/JPY"
    };

    private static final String[] FOREX_PAIRS1 = {
            "EUR/USD"
    };

    private static final String[] CHANNELS = {
            "JPMC", "UBS", "EBS", "CITI", "GS"
    };

    private static final String[] CHANNELS1 = {
            "JPMC",
    };

    private static final String[] INSTRUMENTS1 = {
            "FXSPOT"
    };

    private static final String[] INSTRUMENTS = {
            "FXSPOT", "FXFWD"
    };
    private static final double BASE_PRICE = 1.0;
    private static final double VOLATILITY = 0.05; // 增加波动范围
    private final Random random = new Random();


    // 增加生成频率，每100毫秒生成一次数据
    @Scheduled(fixedRate = 1)
    public void generateAndSendForexData() throws JsonProcessingException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (String pair : FOREX_PAIRS) {
            for (String channel : CHANNELS) {
                for (String instrument : INSTRUMENTS) {
                    MarketData data = generateMarketData(channel, instrument, pair);
                    byte[] bytes = null;
                    try {
                        bytes = new JsonMapper().writeValueAsBytes(data);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                    rabbitMQProducer.sendMessageToExchange1(ROUTING_KEY + pair.replace("/", "."), bytes);
                }

            }

        }
    }

    private MarketData generateMarketData(String channel, String instrument, String pair) {
        double price = BASE_PRICE + (random.nextDouble() - 0.5) * VOLATILITY;
        double volume = 1000000 + random.nextInt(500000);
        return new MarketData(channel, instrument, pair, price, volume, Instant.EPOCH.toEpochMilli());
    }
}
